package uk.ac.sanger;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ParameterMetaData;
import java.util.*;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;

/**
 * Servlet implementation class for Servlet: AsjaTestServlet
 *
 */
public class AsjaTestServlet extends HttpServlet implements Servlet {
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	int connections;  // Variable to track number of visitors..

	public final String BASENAME = "samples";
	public final int NR_OF_PARAMS = 10; // Doesn't include check boxes.
	public final int MAX_CLASS_SIZE = 200;
	String userName;

	// String resources
	public final String s1 = "Guestbook Response Page";
	public final String s2 = "You data has been accepted!";
	public final String s3 = "The annotation has been inserted into the database." + "<BR>";
	public final String s6 = "Error: Sorry, your data has not been saved!<BR>";
	public final String s7 = "Please check database connection!<BR>";
	public final String s8 = "It looks like some information is missing.";
	public final String s9 = "Please go back and fill in the following items so we can continue:";
	public final String s10 = "The annotation has been inserted into the database. " + "<BR>";

	
	//public AsjaTestServlet() {
	//	super();
	//}   	

	public void init(ServletConfig config)
	throws ServletException
	{
		super.init(config);
		connections = 0;
	}

//	Process the HTTP Post request
	boolean error;
	String want_offers = "YES";
	String want_info = "YES";
	Enumeration params;
	String[] entries = {"", "", "", "", "", "", "", "", "", "",
			"", "", "", "", "", "", ""};

//	This servlet keeps track of a lot of strings.
//	These are the names of variables.
	public final String[] parms = {"featureid",
			 					   "featuretype", 
			 					   "method", 
			 					   "segmentid", 
			 					   "start",
			 					   "end",
			 					   "strand",
			 					   "phase",
			 					   "score",
								   "attributes"};

//	These are the same variables, expressed as
//	labels that are written in English and look nicer
//	on the page.
	public final String[] labels = {"Feature id",  // 0
									"Feature type",		// 1
									"Method",				// 2
									"Segment id",	// 3
									"Start",			// 4
									"End",		// 5
									"Strand",		// 6
									"Phase",		// 7
									"Score",				// 8
									"Attributes"			// 9
			
	};

	
//	This is the all-important doPost() method.
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		// This line tells the servlet where the database is.
		//String guestbook = request.getRealPath("guestbook.txt");
		
		//String resourcePath =
		String textfile = "/nfs/team71/phd/ag7/guestbook.txt";
		//String guestbook = getServletContext().getRealPath(resourcePath);
		
		
		String featureid = "";
		try { featureid = request.getParameter("featureid"); } catch (Exception e) { e.printStackTrace(); }
		
		String featuretype = "";
		try { featuretype = request.getParameter("featuretype"); } catch (Exception e) { e.printStackTrace(); }
		
		String method = "";
		try { method = request.getParameter("method"); } catch (Exception e) { e.printStackTrace(); }
		
		String segmentid = "";
		try { segmentid = request.getParameter("segmentid"); } catch (Exception e) { e.printStackTrace(); }
	
		String start = "";
		try { start = request.getParameter("start"); } catch (Exception e) { e.printStackTrace(); }
		
		String end = "";
		try { end = request.getParameter("end"); } catch (Exception e) { e.printStackTrace(); }
		
		String strand = "";
		try { strand = request.getParameter("strand"); } catch (Exception e) { e.printStackTrace(); }
		
		String phase = "";
		try { phase = request.getParameter("phase"); } catch (Exception e) { e.printStackTrace(); }
		
		String score = "";
		try { score = request.getParameter("score"); } catch (Exception e) { e.printStackTrace(); }
		
		String attributes = "";
		try { attributes = request.getParameter("attributes"); } catch (Exception e) { e.printStackTrace(); }
		
					
		PrintWriter pw = new PrintWriter (response.getOutputStream());

		pw.println("<html>");
		pw.println("<head><title>WritebackServlet</title></head>");
		pw.println("<body>");
		
		     
		/*
   // These operations were in a JBuilder tutorial.
   // They worked well, and I might put them to
   // some use someday.
   //
   // pw.print("<P>You are visitor number ");
   // connections++;
   // pw.println(Integer.toString(connections));
   // pw.print(". <BR><BR>");
   // End tutorial print operations.
		 */

		// Find out if the user left any items blank.
		params = request.getParameterNames();

		String s;
		String b = "BLANK";
		String dbString = "";
		error = false;
		try {
			Context env = (Context) new InitialContext().lookup("java:comp/env");
			DataSource dataSource ;
			dataSource = (DataSource) env.lookup("jdbc/SampleDb");

			Connection conn = null;
			if ( dataSource == null)
			{
				System.err.println("could not get dataSource");
			} else 
			{
				System.out.println("*** good news - got the dataSource");
			}


			conn = dataSource.getConnection();
			Statement stat = conn.createStatement();
		    PreparedStatement pstmt = null; 
		
			String sql = "insert into source_00001063(" +
			"featureid, featuretype, method, segmentid, " + 
			"start, end, strand, phase, score, attributes ) "+ 
			"values(?,?,?,?,?,?,?,?,?,?)";
			
		    pstmt = conn.prepareStatement (sql); 
			
			// Check carefully to see if any items are blank.
			for (int n = 0; n < NR_OF_PARAMS; n++) 
			{
					s = request.getParameter(parms[n]);
					if ( s== null)
					{
						System.out.println("did not get a value for " + parms[n]);
					}

				if (s.length() == 0)
				{	// Some fields aren't required, thus
					// can be left blank without generating errors.
					switch (n) 
					{
					// These are the important ones.
					case 0:  // firstname
					case 3:  // lastname
						entries[n] = "ERROR";
						error = true;
						break;
					}   
				}   		

				
				//Float fboxed = Float.parseFloat(s);
				//float f = fboxed.floatValue();
				
				// Set the preparedstatement values
		        pstmt.setString(n+1, s);
		        ParameterMetaData pmtadta; 
		        //pmtadta = pstmt.getParameterMetaData() ; 
				//System.out.println("Post method, check params " + pmtadta.getParameterType ( n+1 ) );
			}
			
			// If any required field has been left blank, 
			// we display an error page.
			if (error == true) 
			{
				params = request.getParameterNames();
				printErrorPage(pw, params, true);	
			}

			// If no important items have been left blank, 
			// we display the Thank You HTML page and update the 
			// database with the user's input.
			else 
			{
				// This is the method that prints the data to the txt file
				// and displays the Thank You HTML page.			
				printData(null, null, dbString, textfile, pw);	

				pw.println("</body></html>");
				pw.close();
				response.setContentType("text/html");
                
				//execute insert statement
				pstmt.executeUpdate();
				
				//check if table was updated
				ResultSet rs = stat.executeQuery("SELECT * FROM source_00001063");
				while(rs.next())
				{
					System.out.println ("Name: " +	rs.getString("featureid"));
				}
				conn.close();
				rs.close();

			}} catch (SQLException e){
				e.printStackTrace();
			}
			catch (Exception e) {
				e.printStackTrace();
				throw new ServletException(e.getMessage());
			}
	
		//finally {
        	//if ( conn != null) {
        		//try {
        		//	conn.close();
        		//} catch (SQLException e){
        			
        		//}
        	//}
        	
       // }
        
		
	}

	/** -------------------------------------------------------------
	 * The printErrorPage() method.
	 *
	 * Opens registration location file and writes 
	 * registration data to file
	 *
	 * @param pw PrintWriter.
	 * @param Vector arg parameter Vector.
	 * @boolean errorStatus.
	 * @return Boolean indicating whether database entry was  
	 * successful.
	 * @exception IOException When opening, reading from, or
	 * writing the output stream to the registration file.
	 */

	//////////////////////////////////////////////////////////
	//
	// This method outputs error messages to the browser page.
	//
	public void printErrorPage(PrintWriter pw, Enumeration e,
			boolean errorStatus)   throws IOException
			{
		// This loop prints the error message.
		pw.print("<H1>Sorry!</H1>");

		pw.print("<BR>");
		pw.print(s8 + "<BR>");
		pw.println(s9 + "<BR><P>");

		for (int n = 0; n < NR_OF_PARAMS; n++) {
			if (entries[n] == "ERROR") {
				pw.println(labels[n]);
				pw.print("<BR>");
				entries[n] = "";
			}	
		}

		pw.println("</BODY></HTML>");
		pw.flush();
		pw.close();
		return;
			} // end of printErrorPage()

	/** -----------------------------------------------------------------
	 * @ printData() method.
	 * 
	 * @ Displays a Thank You page and writes 
	 *   data to the database.
	 * 
	 * @param dt date -- not used in this implemementation.
	 * @param loc  -- not used in this implemementation.
	 * @param rData Data string.
	 * @param aFile Data file name.
	 * @return Boolean indicating whether data was  
	 * successfully written.
	 *
	 * @exception IOException When opening, reading from, or
	 *  writing the output stream to the database.
	 */ 
	//////////////////////////////////////////////////////////
	//
	// Display a Thank You page and add 
	// the user's input to the database.
	//
	public synchronized boolean printData(String dt, String loc, 
			String rData, String aFile, PrintWriter pw) 
	throws IOException
	{
		boolean done = false;
		int numLns = 0;
		String line = null, regLine = null;
		String fileLine = null;
		String regFile = aFile;
		String regData = rData;
		BufferedReader readFile = null;
		Vector lines = new Vector();

		// Set up a buffer to read out items that are
		// already in the database.
		
		try
		{
			String bgcolor ="#d0d0d0";
			String fg ="yellow";
			
			pw.print("<body \bgcolor=" + bgcolor + ">");
			// Heading for the Thank You page.
			pw.print("<H2>Thanks for submitting your data!!!</H2>");

			pw.print(s10);
			pw.print("</body>");

			// This is a test.
			// pw.println("RegData: " + regData + "<BR>");

			readFile = new BufferedReader(new FileReader(regFile));
		}
		catch(Exception e)
		{
			pw.println(s6);
			pw.println(s7);
			pw.println(e.toString());
			pw.flush();
			return done;
		}
		//////////////////////////////////////////////////
		//
		// Copy all current lines in the database 
		// into a Vector. How inefficient! We need
		// an RDBMS.
		//
		while((regLine = readFile.readLine()) != null) {
			lines.addElement((Object)regLine);
		}
		pw.flush();
		readFile.close();

		// Check to see if we can write to the database.
		try {
			pw = new PrintWriter(new FileWriter(regFile));
		} catch(Exception e) {
			pw.println("Error: Could not write to file " + regFile);
			pw.println(e.toString());
			pw.flush();
			return done;
		}

		//This loop adds the user's input to the database;
		if((numLns = lines.size()) > 0)
		{
			for(int i = 0;i < numLns;i++)
			{
				line = (String)lines.elementAt(i);
				pw.println(line); 
			}
			// This is the line that does the writing
			// to the database file.
			pw.println(regData);
			done = true;
		}
		pw.flush();
		pw.close();

		return done;

	} // end of printData()  	  	


	public void doGet(HttpServletRequest request,
	        HttpServletResponse response)
	        throws IOException, ServletException
	    {
		try
		{
	        response.setContentType("text/html");
	        PrintWriter out = response.getWriter( );
	        out.println ("<html><body>Hello777 new World!</body></html>");
	        out.println("<HTML>");
	        out.println("<HEAD>");
	        out.println("<TITLE>");
	        out.println("Servlet Sample");
	        out.println("</TITLE>");
	        out.println("</HEAD>");
	        out.println("<BODY>");
	        out.println("<H1>");
	        out.println("Servlet Sample");
	        out.println("</H1>");
	        out.println("Hello world! 22");
	        out.println("</BODY>");
	        out.println("</HTML>");
	        
	        Context env = (Context) new InitialContext().lookup("java:comp/env");
	        DataSource dataSource ;
	    	dataSource = (DataSource) env.lookup("jdbc/SampleDb");
	    	
	        Connection conn = null;
	        if ( dataSource == null){
	        	System.err.println("could not get dataSource");
	        } else {
	        	System.out.println("*** good news - got the dataSource");
	        }

	        
	        try {
	        	conn = dataSource.getConnection();
	        	System.out.println("got conn");
	        	Statement stat = conn.createStatement();

	            System.out.println ("Information :");
	            ResultSet rs = stat.executeQuery ("SELECT * FROM source_00001063");
	            while(rs.next())
	            {
	            	System.out.println ("Name: " +	rs.getString("featureid"));
	            }
	            
	            stat.close();
	            rs.close();
	            
	        } catch (SQLException e){
	        	e.printStackTrace();
	        } finally {
	        	if ( conn != null) {
	        		//try {
	        		//	conn.close();
	        		//} catch (SQLException e){
	        			
	        		//}
	        	}
	        	
	        }
	        
	        
		}
		catch (Exception e) {
			e.printStackTrace();
			throw new ServletException(e.getMessage());
		}
	     }
	
	//protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	// TODO Auto-generated method stub
	//}   	  	    
}